package org.obm.delivery.cassandra;

import java.util.List;

import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.dom.MessageBuilder;
import org.apache.james.mime4j.dom.MessageBuilderFactory;
import org.obm.delivery.cassandra.filters.IFilterFactory;
import org.obm.lmtp.backend.IDeliveryAgent;
import org.obm.lmtp.backend.ILmtpBackendFactory;
import org.obm.lmtp.backend.IMailboxValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.aliasource.utils.RunnableExtensionLoader;

/**
 * This factory creates delivery agents taking emails from lmtp and storing them
 * into cassandra.
 * 
 * @author tom
 * 
 */
public class DeliveryFactory implements ILmtpBackendFactory {

	private static final Logger logger = LoggerFactory
			.getLogger(DeliveryFactory.class);

	private IFilterFactory ff;

	private MessageBuilder builder;

	public DeliveryFactory() {
		try {
			RunnableExtensionLoader<IFilterFactory> r = new RunnableExtensionLoader<IFilterFactory>();
			List<IFilterFactory> ffs = r.loadExtensions(Activator.PLUGIN_ID,
					"filterfactory", "filter_factory", "implementation");
			if (ffs.size() == 0) {
				logger.error("No filter factory implementation found");
			} else {
				ff = ffs.get(0);
			}
		} catch (Throwable t) {
			logger.error("error loading delivery agent", t);
		}
		
		try {
			MessageBuilderFactory mbf = MessageBuilderFactory.newInstance();
			builder = mbf.newMessageBuilder();
		} catch (MimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public IDeliveryAgent getDeliveryAgent() {
		return new CassandraAgent(ff, builder);
	}

	@Override
	public IMailboxValidator getValidator() {
		return null;
	}

}
